// 转为unicode 编码
// 使用于php josn数组在js中进行中文编码
stylePlugins.encodeUnicode = function (str)
{  
    var res = [];  
    for ( var i=0; i<str.length; i++ ) {  
    res[i] = ( "00" + str.charCodeAt(i).toString(16) ).slice(-4);  
    }  
    return "\\u" + res.join("\\u");  
}  
  
// 解码  
// 使用于php josn数组在js中进行中文解码
stylePlugins.decodeUnicode = function (str)
{  
    str = str.replace(/\\/g, "%");  
    return unescape(str);  
}
/***************************END****************************/

/**四级级联下拉菜单插件**/
function fourSelect(config,fourSelectData) {
	var $s1 = $("#" + config.s1);
	var $s2 = $("#" + config.s2);
	var $s3 = $("#" + config.s3);
	var $s4 = $("#" + config.s4);
	var v1 = config.v1 ? config.v1 : null;
	var v2 = config.v2 ? config.v2 : null;
	var v3 = config.v3 ? config.v3 : null;
	var v4 = config.v4 ? config.v4 : null;
	$.each(fourSelectData, function(k, v) {
		appendOptionTo($s1, k, v.val, v1);
	});
	$s1.change(function() {
		$s2.html("");
		if (this.selectedIndex == -1)
			return;
		var s1_curr_val = this.options[this.selectedIndex].value;
		$.each(fourSelectData, function(k, v) {
			if (s1_curr_val == v.val) {
				if (v.items) {
					$.each(v.items, function(k, v) {
						appendOptionTo($s2, k, v.val, v2);
					});
				}
			}
		});
		if ($s2[0].options.length == 0) {
			appendOptionTo($s2, "...", "", v2);
		}
		$s2.change();
	}).change();
	$s2.change(function() {
		$s3.html("");
		if (this.selectedIndex == -1)
			return;
		var s1_curr_val = $s1[0].options[$s1[0].selectedIndex].value;
		var s2_curr_val = this.options[this.selectedIndex].value;
		$.each(fourSelectData, function(k, v) {
			if (s1_curr_val == v.val) {
				if (v.items) {
					$.each(v.items, function(k, v) {
						if (s2_curr_val == v.val) {
							if (v.items) {
								$.each(v.items, function(k, v) {
									appendOptionTo($s3, k, v.val, v3);
								});
							}
						}
					});
				}
			}
		});
		if ($s3[0].options.length == 0) {
			appendOptionTo($s3, "...", "", v3);
		}
		$s3.change();
	}).change();
	$s3.change(function() {
		$s4.html("");
		if (this.selectedIndex == -1)
			return;
		var s1_curr_val = $s1[0].options[$s1[0].selectedIndex].value;
		var s2_curr_val = $s2[0].options[$s2[0].selectedIndex].value;
		var s3_curr_val = this.options[this.selectedIndex].value;
		$.each(fourSelectData, function(k, v) {
			if (s1_curr_val == v.val) {
				if (v.items) {
					$.each(v.items, function(k, v) {
						if (s2_curr_val == v.val) {
							if (v.items) {
								$.each(v.items, function(k, v) {
									if (s3_curr_val == v.val) {
										if (v.items) {
											$.each(v.items, function(k, v) {
												appendOptionTo($s4, k, v, v4);
											});
										}
									}
								});
							}
						}
					});
				}
			}
		});
		if ($s4[0].options.length == 0) {
			appendOptionTo($s4, "...", "", v4);
		}
	}).change();
	function appendOptionTo($o, k, v, d) {
		var $opt = $("<option>").text(k).val(v);
		if (v == d) {
			$opt.attr("selected", "selected")
		}
		$opt.appendTo($o);
	}
}
/***************************END****************************/

/**多图上传钩子**/
function st_upduoimg(dataname,num,fieldvalue) {
	var input = document.getElementById("upgteimg"+dataname);
	var showui = document.getElementById("showui"+dataname);
	var result;
	var dataArr = []; // 储存所选图片的结果(文件名和base64数据)  
	var fd; //FormData方式发送请求    
	var showinput = document.getElementById("showinput"+dataname);
	var oSubmit = document.getElementById("submit"+dataname);
	send();
	if(fieldvalue){
		var fieldvalueArr=fieldvalue.split(",");
		for(var i=0; i<fieldvalueArr.length; i++){
			dataArr[i] = {
				name: fieldvalueArr[i], //获取文件名    
				base64: fieldvalueArr[i] //reader.readAsDataURL方法执行完后，base64数据储存在reader.result里    
			};
		}
		opimgdata();
	}
	function show() {}
	//监听展示图片的ul,执行判断是否隐藏
	showui.addEventListener("click", function() {
		show();
	});
	if(typeof FileReader === 'undefined') {
		alert("抱歉，你的浏览器不支持 FileReader");
		input.setAttribute('disabled', 'disabled');
	} else {
		input.addEventListener('change', readFile, false);
	}

	function readFile() {
		fd = new FormData();
		var iLen = this.files.length;
		var index = 0;
		var currentReViewImgIndex = 0;
		for(var i = 0; i < iLen; i++) {
			//判断上传文件格式
			if(!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)) {
				return alert("上传的图片格式不正确，请重新选择");
			}
			var reader = new FileReader();
			reader.index = i;
			fd.append(i, this.files[i]);
			reader.readAsDataURL(this.files[i]); //转成base64    
			reader.fileName = this.files[i].name;
			reader.onload = function(e) {
				
				// 上传数量限制
				if(dataArr.length >= num) {
					alert('最多只能上传'+num+'张图片');
					return false;
				}
				
				var imgMsg = {
					name: this.fileName, //获取文件名    
					base64: this.result //reader.readAsDataURL方法执行完后，base64数据储存在reader.result里    
				}
				dataArr.push(imgMsg);
				for(var j = 0; j < dataArr.length; j++) {
					currentReViewImgIndex = j
				}
				result = '<div class="showdiv"><img class="left" src="/plugins/modulepara/configdata/uploadpicduo2/Arrow_left.svg" /><img class="center" src="/plugins/modulepara/configdata/uploadpicduo2/delete.svg" /><img class="right" src="/plugins/modulepara/configdata/uploadpicduo2/Arrow_right.svg" /></div><img id="srcimgid' + dataname + currentReViewImgIndex + '" class="showimg" src="' + this.result + '" />';

				var li = document.createElement('li');
				li.innerHTML = result;
				showui.appendChild(li);
				show();
				send();
				opimgdata();
				
				index++;

			}
		}
	}
	
	function opimgdata(){
		for(var opj = 0; opj < dataArr.length; opj++) {
			var getdiv = document.getElementById("showui");
			var getli = getdiv.getElementsByTagName('li')[opj];
			var left = getli.getElementsByTagName('img')[0];// 左移
			var center = getli.getElementsByTagName('img')[1];// 删除
			var right = getli.getElementsByTagName('img')[2];// 右移
			var src = getli.getElementsByTagName('img')[3];// 图片地址
			left.onclick = function(num) {
				return function() {
					if(num == 0) {
	
					} else {
						var list = 0;
						for(var j = 0; j < dataArr.length; j++) {
							list = j
						}
						dataArr.splice(up, 0, dataArr[num]);
						dataArr.splice(num + 1, 1)
						var up = num - 1;
						for(var j = 0; j < list + 1; j++) {
							$("#srcimgid" + dataname + j + "").attr("src", dataArr[j].base64)
						}
						send();
						console.log(dataArr)
					}
				}
			}(opj)
	
			center.onclick = function(num) {
				return function() {
					getli.remove(); // 在页面中删除该图片元素  
					dataArr.splice(num, 1);
					send();
				}
			}(opj)
	
			right.onclick = function(num) {
				return function() {
	
					var list = 0;
					for(var j = 0; j < dataArr.length; j++) {
						list = j
					}
	
					dataArr.splice(list + 1, 0, dataArr[num]);
					dataArr.splice(num, 1)
					var down = num - 1;
					var datalist = list+1;
					for(var j = 0; j < datalist; j++) {
						$("#srcimgid" + dataname + j + "").attr("src", dataArr[j].base64)
					}
					send();
				}
			}(opj)	
		}
	}

	function send() {
		var	inputdata = "";
		for(var j = 0; j < dataArr.length; j++) {
			inputdata += '<input name="st_duopic'+dataname+'[]" type="hidden" value="' + dataArr[j].base64 + '" />';
		}
		showinput.innerHTML = inputdata;
	}

	oSubmit.onclick = function() {
		if(!dataArr.length) {
			return alert('请先选择文件');
		}
		send();
	}

	$('#showui'+dataname).on('DOMNodeInserted', function() {
		show();
	})
}
/***************************END****************************/

/**图片上传钩子**/
function st_uploadpic(dataname,phpurl,picdir)
{
    $("#uploadBtn"+dataname).change(function(){
        if (typeof (FileReader) != "undefined") {
            var formdata = new FormData();
            var v_this = $(this);
            var fileObj = v_this.get(0).files;
            var img = $("#imgPath"+dataname);
            formdata.append("smfile", fileObj[0]);
            $.ajax({
                url:phpurl,
                type: "POST",
                dataType: "JSON",
                async: false,
                data : formdata,
                cache : false,
                contentType : false,
                processData : false,
                timeout : 5000,
                success:function (data) {
					if(data != '[object Object]'){
						var data = eval('('+data+')');
					}
                    if(data.code == "success"){
                        img.attr('src', picdir+data.data.url);
                        img.css('display','block');
                        $("#uploadFile"+dataname).val(data.data.url);
						function isExitsFunction(funcName) {
						  try {
							if (typeof(eval(funcName)) == "function") {
							  return true;
							}
						  } catch(e) {}
						  return false;
						}
						if(isExitsFunction("st_uploadpichtml")) {
							st_uploadpichtml(dataname,data.data);
						}
                    }else{
                        alert("上传错误!!");
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(errorThrown)
                }
            });
        }
    });
}
/***************************END****************************/

/**文件上传钩子**/
function st_uploadfile(dataname,phpurl) { 
	var xhr;//异步请求对象
	var ot; //时间
	var oloaded;//大小
	document.getElementById("videofile"+dataname).addEventListener('change', UpladFile, false);
	$("#uploadcontent"+dataname+" .upbut").click(function(){
		subvideo();	
	});
	//上传文件方法
	function UpladFile() {
		var fileObj = document.getElementById("videofile"+dataname).files[0]; // js 获取文件对象
		if(fileObj.name){
			$("#uploadcontent"+dataname+" .videoName").text(fileObj.name);
		}else{
			alert("请选择文件");
		}
	}
	/*点击提交*/
	function subvideo(){
		var fileObj = document.getElementById("videofile"+dataname).files[0]; // js 获取文件对象
		if(fileObj==undefined||fileObj==""){
			alert("请选择文件");
			return false;
		};
		var url = phpurl; // 接收上传文件的后台地址 
		var form = new FormData(); // FormData 对象
		form.append("mf", fileObj); // 文件对象 
		xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
		xhr.open("post", url, true); //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
		xhr.onload = uploadComplete; //请求完成
		xhr.onerror = uploadFailed; //请求失败
		xhr.upload.onprogress = progressFunction; //【上传进度调用方法实现】
		xhr.upload.onloadstart = function() { //上传开始执行方法
			ot = new Date().getTime(); //设置上传开始时间
			oloaded = 0; //设置上传开始时，以上传的文件大小为0
		};
		xhr.send(form); //开始上传，发送form数据
	}
	
	//上传进度实现方法，上传过程中会频繁调用该方法
	function progressFunction(evt) { 
		// event.total是需要传输的总字节，event.loaded是已经传输的字节。如果event.lengthComputable不为真，则event.total等于0
		if(evt.lengthComputable) {
			$("#uploadcontent"+dataname+" .el-progress__text").css("display","block");// 显示百分比进度条
			$("#uploadcontent"+dataname+" .el-progress--line").css("display","none");// 显示进度条速度，默认已关闭显示
			/*进度条显示进度*/
			$("#uploadcontent"+dataname+" .el-progress-bar__inner").css("width", Math.round(evt.loaded / evt.total * 100) + "%");
			$("#uploadcontent"+dataname+" .el-progress__text").html(Math.round(evt.loaded / evt.total * 100)+"%");   
		}
	
		var time = $("#uploadcontent"+dataname+" .time");
		var nt = new Date().getTime(); //获取当前时间
		var pertime = (nt - ot) / 1000; //计算出上次调用该方法时到现在的时间差，单位为s
		ot = new Date().getTime(); //重新赋值时间，用于下次计算
	
		var perload = evt.loaded - oloaded; //计算该分段上传的文件大小，单位b 
		oloaded = evt.loaded; //重新赋值已上传文件大小，用以下次计算
	
		//上传速度计算
		var speed = perload / pertime; //单位b/s
		var bspeed = speed;
		var units = 'b/s'; //单位名称
		if(speed / 1024 > 1) {
			speed = speed / 1024;
			units = 'k/s';
		}
		if(speed / 1024 > 1) {
			speed = speed / 1024;
			units = 'M/s';
		}
		speed = speed.toFixed(1);
		//剩余时间
		var resttime = ((evt.total - evt.loaded) / bspeed).toFixed(1);
		time.innerHTML = '上传速度：' + speed + units + ',剩余时间：' + resttime + 's';
		if(bspeed == 0)
			time.innerHTML = '上传已取消';
	}
	//上传成功响应
	function uploadComplete(evt) {
		//服务断接收完文件返回的结果  注意返回的字符串要去掉双引号
		if(evt.target.responseText){
			var str = evt.target.responseText;
			alert("上传成功！");
			$("#uploadcontent"+dataname+" .videoName").hide();
			$("#uploadcontent"+dataname+" .preview").append("<span>"+str+"</span>");
			$("#upfileurl"+dataname).val(str);
			function isExitsFunction(funcName) {
			  try {
				if (typeof(eval(funcName)) == "function") {
				  return true;
				}
			  } catch(e) {}
			  return false;
			}
			if(isExitsFunction("st_uploadfilehtml")) {
				st_uploadfilehtml(dataname,str);
			}
		}else{
			alert("上传失败");
		}
	}
	//上传失败
	function uploadFailed(evt) {
		alert("上传失败！");
	}
}
/***************************END****************************/